import requests

# 服务器运行在WSL中，Windows可以通过localhost访问
# WSL 1 和 WSL 2 的新版本都支持这一点
SERVER_URL = "http://localhost:5000/get_consumption"

def get_consumption_from_server(month, time):
    params = {
        'month': month,
        'time': time
    }
    
    try:
        response = requests.get(SERVER_URL, params=params)
        
        # 检查请求是否成功
        if response.status_code == 200:
            return response.json()
        else:
            # 打印服务器返回的错误信息
            error_data = response.json()
            return {"error": f"Server responded with status {response.status_code}: {error_data.get('error', 'Unknown error')}"}
            
    except requests.exceptions.ConnectionError:
        return {"error": "Connection failed. Is the server running in WSL?"}
    except Exception as e:
        return {"error": f"An unexpected error occurred: {str(e)}"}

if __name__ == "__main__":
    print("--- Energy Consumption Client ---")
    print("Enter a month (1-12) and a time (0, 0.5, ..., 23.5) to query.")
    print("Press Ctrl+C to exit.")
    
    while True:
        try:
            # 获取用户输入
            month_input = int(input("\nEnter month (1-12): "))
            time_input = float(input("Enter time (0.0 - 23.5): "))
            
            # 输入验证
            if not (1 <= month_input <= 12):
                print("Error: Month must be between 1 and 12.")
                continue
            if not (0 <= time_input <= 23.5):
                print("Error: Time must be between 0.0 and 23.5.")
                continue
            
            # 将月份格式化为两位数的字符串，例如 1 -> "01"
            month_str = f"{month_input:02d}"
            
            # 发送请求并获取结果
            result = get_consumption_from_server(month_str, time_input)
            
            # 打印结果
            if "error" in result:
                print(f"Error: {result['error']}")
            else:
                print("\n--- Server Response ---")
                print(f"  Month: {result['month']}")
                print(f"  Requested Time: {result['requested_time']}")
                print(f"  Data for Hour: {result['hour_of_day']}")
                print(f"  Energy Consumption: {result['energy_consumption']:.2f}")
                print("-----------------------")

        except ValueError:
            print("Invalid input. Please enter numbers only.")
        except KeyboardInterrupt:
            print("\nExiting client.")
            break